package com.tanhua.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVO;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.PublishVO;
import com.tanhua.domain.vo.VideoVO;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.PublishApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideosApi;
import com.tanhua.domain.UserStatus;
import com.tanhua.mapper.UserStatusMapper;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UsersService extends ServiceImpl<UserStatusMapper,UserStatus> {

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private PublishApi publishApi;
    @Reference
    private VideosApi videosApi;
    @Reference
    private CommentApi commentApi;
    @Autowired
    private UserStatusMapper userStatusMapper;


    /**
     * 分页查询所有用户
     * @param page 当前页码
     * @param pagesize 展示条数
     * @return
     */
    public ResponseEntity getUsers(int page, int pagesize) {
        //分页查询用户列表
        IPage<UserInfo> iPage = userInfoApi.findList(page, pagesize);

        //封装结果数据
        PageResult<UserInfo> pageResult = new PageResult<>();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setCounts((int) iPage.getTotal());
        pageResult.setPages((int) iPage.getPages());
        pageResult.setItems(iPage.getRecords());

        return ResponseEntity.ok(pageResult);
    }

    /**
     *  查询用户详细信息
     * @param userID 用户id
     * @return
     */
    public ResponseEntity getUser(Long userID) {
        //查询用户详细信息
        UserInfo userInfo = userInfoApi.findById(userID);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 分页查询用户动态信息
     * @param page 当前页码
     * @param pagesize 展示条数
     * @param uid 用户id
     * @param state 审核状态
     * @return
     */
    public ResponseEntity findMessages(int page, int pagesize, Long uid, String state) {
        //分页查询用户动态列表
        PageResult<Publish> pageResult = publishApi.findPublishList(page, pagesize, uid, state);
        //转换成vo
        List<PublishVO> voList = new ArrayList<>();
        for (Publish publish : pageResult.getItems()) {
            PublishVO vo = new PublishVO();
            //把publish封装到vo中
            BeanUtils.copyProperties(publish, vo);
            vo.setId(publish.getId().toHexString());
            vo.setImageContent(publish.getMedias().toArray(new String[]{}));
            vo.setDistance("0.05km");
            vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));

            //封装发布人信息
            UserInfo userInfo = userInfoApi.findById(publish.getUserId());
            vo.setNickname(userInfo.getNickname());
            vo.setAvatar(userInfo.getAvatar());
            vo.setTags(userInfo.getTags().split(","));

            voList.add(vo);
        }

        //构造返回值
        PageResult<PublishVO> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);

        return ResponseEntity.ok(voPageResult);
    }

    /**
     * 查询动态详情
     * @param publishId 动态id
     * @return
     */
    public ResponseEntity findPublishById(String publishId) {
        //根据动态id查询动态
        Publish publish = publishApi.findById(publishId);

        //转换成vo
        PublishVO vo = new PublishVO();
        //把publish封装到vo中
        BeanUtils.copyProperties(publish, vo);
        vo.setId(publish.getId().toHexString());
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        vo.setDistance("0.05km");
        vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));

        //封装发布人信息
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        BeanUtils.copyProperties(userInfo, vo);
        vo.setTags(userInfo.getTags().split(","));

        return ResponseEntity.ok(vo);
    }

    /**
     * 评论列表
     * @param page 当前页码
     * @param pagesize 展示条数
     * @param messageID 动态id
     * @return
     */
    public ResponseEntity findCommentList(int page, int pagesize, String messageID) {
        //查询评论列表
        PageResult<Comment> pageResult = commentApi.findComment(messageID, page, pagesize);
        if (pageResult.getItems().size() < 1) {
            return ResponseEntity.ok(null);
        }
        //转换成VO
        List<CommentVO> voList = new ArrayList<>();
        for (Comment comment : pageResult.getItems()) {
            CommentVO vo = new CommentVO();
            //评论信息封装到vo
            BeanUtils.copyProperties(comment,vo);
            vo.setId(comment.getId().toHexString());
            vo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));
            //封装评论人信息
            UserInfo userInfo = userInfoApi.findById(comment.getUserId());
            vo.setNickname(userInfo.getNickname());
            vo.setAvatar(userInfo.getAvatar());

            voList.add(vo);
        }
        //构造返回值
        PageResult<CommentVO> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);

        return ResponseEntity.ok(voPageResult);
    }

    /**
     * 视频列表
     * @param page 当前页码
     * @param pagesize 展示条数
     * @param uid 用户id
     * @return
     */
    public ResponseEntity findVideos(int page, int pagesize, Long uid) {
        //查询视频列表
        PageResult<Video> pageResult = videosApi.findVideoList(page, pagesize, uid);
        //转换成VO
        List<VideoVO> voList = new ArrayList<>();
        for (Video video : pageResult.getItems()) {
            VideoVO vo = new VideoVO();
            vo.setId(video.getId().toHexString());
            vo.setCover(video.getPicUrl());
            vo.setSignature(video.getText());
            vo.setVideoUrl(video.getVideoUrl());
            //封装发布人信息
            UserInfo userInfo = userInfoApi.findById(video.getUserId());
            BeanUtils.copyProperties(video, vo);

            voList.add(vo);
        }
        //构造返回值
        PageResult<VideoVO> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);

        return ResponseEntity.ok(voPageResult);
    }

    /**
     * 分页查询某一用户的动态列表
     * @param page 页码
     * @param pagesize 查询几条
     * @param
     * @param state 动态的审核状态
     */
    public ResponseEntity findMovementsList(int page, int pagesize, Long uid, Integer state) {
        //1. 远程调用API，分页查询动态列表
        PageResult<Publish> pageResult = publishApi.findPublishListByState(page, pagesize, uid, state);

        //2. 转换成VO
        List<Publish> publishList = pageResult.getItems();
        List<PublishVO> voList = new ArrayList<>();
        for (Publish publish : publishList) {
            PublishVO vo = new PublishVO();

            //封装动态发布者的信息
            UserInfo userInfo = userInfoApi.findById(publish.getUserId());
            BeanUtils.copyProperties(userInfo, vo);
            vo.setTags(userInfo.getTags().split(","));

            //封装动态信息
            BeanUtils.copyProperties(publish, vo);
            vo.setId(publish.getId().toHexString());
            vo.setImageContent(publish.getMedias().toArray(new String[]{}));
            vo.setDistance("50米");
            vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));

            voList.add(vo);
        }

        //3. 构造返回值
        PageResult<PublishVO> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);
        return ResponseEntity.ok(voPageResult);
    }

    /**
     * @param userId 用户id
     * @param freezingTime 冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
     * @param freezingRange 冻结范围，1为冻结登录，2为冻结发言，3为冻结发布动态
     * @param reasonsForFreezing 冻结原因
     * @param frozenRemarks 冻结备注
     * @return
     */
    public ResponseEntity freeze(Integer userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
       try{
        UserInfo userInfo = userInfoApi.findById(userId.longValue());
        //设置用户状态为封禁状态
        userInfo.setUserStatus("2");
        userInfoApi.update(userInfo);
        UserStatus banned = new UserStatus();
        banned.setUserId(userId);
        banned.setFreezingTime(freezingTime);
        banned.setFreezingRange(freezingRange);
        banned.setReasonsForFreezing(reasonsForFreezing);
        banned.setFrozenRemarks(frozenRemarks);
           //冻结时间到哪天
           Calendar cal = null;
           if(freezingTime==1){
               cal = Calendar.getInstance();
               //日期加3天
               cal.add(Calendar.DAY_OF_MONTH, +3);
               Date time = cal.getTime();
               banned.setUnFreezeTime(time);
           }else if(freezingTime==2){
               cal = Calendar.getInstance();
               //日期加7天
               cal.add(Calendar.DAY_OF_MONTH, +7);
               Date time = cal.getTime();
               banned.setUnFreezeTime(time);
           }else if(freezingTime==3){
               cal = Calendar.getInstance();
               //日期加999年
               cal.add(Calendar.YEAR, +999);
               Date time = cal.getTime();
               banned.setUnFreezeTime(time);
           }
        userStatusMapper.insert(banned);
       } catch (Exception e) {
           e.printStackTrace();
           String message = "冻结失败,请重试";
           return ResponseEntity.ok(message);
       }
        String message = "账号冻结成功";
        return ResponseEntity.ok(message);
    }

    /**
     * 解冻
     * @param userId 用户Id
     * @param reasonsForThawing 解冻原因
     * @return
     */
    public ResponseEntity unFreeze(Integer userId, String reasonsForThawing) {
        try {
            //查询获得userInfo对象 修改状态
            UserInfo userInfo = userInfoApi.findById(userId.longValue());
            userInfo.setUserStatus("1");
            userInfoApi.update(userInfo);

            //删除用户冻结表
            QueryWrapper<UserStatus> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId);
            userStatusMapper.delete(wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("解冻失败,请重试");
        }
        return ResponseEntity.ok("账号解冻成功");
    }

    /**
     * 动态通过
     * @param ids
     * @return
     */
    public ResponseEntity pass(String[] ids) {
        HashMap hashMap = new HashMap();
        if (ids != null) {
            for (String id : ids) {
                publishApi.updateStates(id,1);
            }
        }

        hashMap.put("message", "ok");
        return ResponseEntity.ok(hashMap);
    }

    /**
     * 动态拒绝
     * @param ids
     * @return
     */
    public ResponseEntity reject(String[] ids) {
        HashMap hashMap=new HashMap();
        if (ids != null){
            for (String id : ids) {
                publishApi.updateStates(id,2);
            }
        }
        hashMap.put("message","ok");
        return ResponseEntity.ok(hashMap);
    }
}
